<template>
  <div class="deck">
    <van-nav-bar
      title="桌台绑定"
      left-arrow
      @click-left="$router.back()"
      class="top_bar"
    />
    <div class="content" v-if="shopList.length > 0">
      <div class="shop_address" @click="showPicker = true">
        {{ shopMsg.shopName }}<van-icon name="arrow-down" />
      </div>
      <div class="class_ify" v-if="areasList.length > 0">
        <van-tree-select
          :items="areasList"
          :active-id.sync="activeId"
          :main-active-index.sync="activeIndex"
          height="100%"
          @click-nav="changeArea"
        >
          <template #content>
            <div v-if="tabList.length > 0">
              <div
                class="select_div"
                v-for="(item, index) in tabList"
                :key="index"
              >
                <div class="desk_num">{{ item.tableNo }}桌</div>
                <div class="bind" @click="bindDesk(item)" v-if="!item.codeNo">
                  绑定二维码<van-icon name="arrow" />
                </div>
                <div class="is_bind" @click="unBind(item)" v-else>
                  已绑定{{ item.codeNo }}<van-icon name="arrow" />
                </div>
              </div>
            </div>
            <div v-else class="no_content" style="height: 80vh">
              <van-empty
                class="custom-image"
                :image="require('@/assets/img/flow/set.png')"
                description="暂未创建桌台管理，请到商户后台创建"
              />
            </div>
          </template>
        </van-tree-select>
      </div>
      <div v-if="areasList.length < 1" class="no_content" style="height: 80vh">
        <van-empty
          class="custom-image"
          :image="require('@/assets/img/flow/set.png')"
          description="暂未创建桌台管理，请到商户后台创建"
        />
      </div>
      <van-popup
        v-model="showPicker"
        position="bottom"
        @click-overlay="closePop"
      >
        <div style="max-height: 50vh" class="pop_shop">
          <div class="pop_top">
            <div><van-icon name="cross" @click="closePop" /></div>
            <div>选择门店</div>
            <div style="color: #ffb72f" @click="confirmShop">确定</div>
          </div>
          <div v-if="showPicker" class="pop_conent">
            <van-radio-group v-model="thirdRadio">
              <van-radio
                class="pop_radio"
                v-for="item in shopList"
                :name="item.id"
                :key="item.id"
              >
                <template #icon="props">
                  <img
                    class="img-icon"
                    :src="props.checked ? isCheck : noCheck"
                  /> </template
                >{{ item.name }}
              </van-radio>
            </van-radio-group>
          </div>
        </div>
      </van-popup>
    </div>
    <div class="no_content" v-else>
      <van-empty
        class="custom-image"
        :image="require('@/assets/img/flow/set.png')"
        description="暂未创建桌台管理，请到商户后台创建"
      />
      <!-- 
      {{JSON.stringify(shopList)}}
      <van-button @click="$router.push('Step3')">跳转</van-button>
      <van-button button @click="noScan">扫码</van-button> -->
    </div>
  </div>
</template>
<script>
import { Dialog } from "vant";
import {
  getShopList,
  getAreas,
  getDesk,
  bindDesk,
  unBindDesk,
} from "@/api/flow/index";
export default {
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      areasList: [],
      isCheck: require("../../../assets/img/flow/is_check.png"),
      noCheck: require("../../../assets/img/flow/no_check.png"),
      thirdRadio: 0,
      activeId: 1,
      activeIndex: 0,
      areaId: "",
      tabList: [],
      value: "",
      shopList: [],
      showPicker: false,
      shopName: "",
      shopMsg: {
        shopName: "",
        shopId: "",
      },
      snCode: "11",
      deskPar: {},
      dialogType: "",
    };
  },
  mounted() {
    window.AndroidInfo = this.AndroidInfo;
    // this.getLocaShop();
    this.fetData();
  },
  methods: {
    //安卓扫码回调
    AndroidInfo(data) {
      // console.log(data, 'message--')
      this.setDeskCode(data, 1);
    },
    // 切换区域的时候
    changeArea() {
      let { activeIndex, areasList } = this;
      this.areaId = areasList[activeIndex].id;
      this.getDesk();
    },
    // 关闭门店选择
    confirmShop() {
      let { shopList, thirdRadio } = this;
      this.shopMsg.shopId = thirdRadio;
      shopList.forEach((el, index) => {
        if (el.id == thirdRadio) this.shopMsg.shopName = shopList[index].name;
      });
      this.showPicker = false;
      this.getAreas();
    },
    closePop() {
      this.thirdRadio = this.shopMsg.shopId;
      this.showPicker = false;
    },
    // 解绑
    unBind(item) {
      console.log(item);
      Dialog.confirm({
        title: "提示",
        message: `是否要解除${item.tableNo}的二维码绑定`,
        className: "dialog_class",
        confirmButtonText: "解除",
        confirmButtonColor: "#ffb72f",
      }).then(() => {
        unBindDesk({ codeNo: item.codeNo }).then((res) => {
          let {data} = res
          if (data.code == 0 && data.msg == "success") {
            Dialog.alert({
              title: "提示",
              message: `解绑成功`,
              confirmButtonColor: "#ffb72f",
            }).then(() => {
              this.getDesk();
            });
          } else {
            Dialog.alert({
              title: "提示",
              message: `${data.msg}`,
              confirmButtonColor: "#ffb72f",
            });
          }
        });
      });
    },
    async fetData() {
       let {shopId,userId} = JSON.parse(localStorage.getItem('Urldata'))
      await getShopList({shopId,userId}).then((res) => {
        let { data } = res;
        if (data.code == 0) {
          this.shopList = data.data.list;
          if(this.shopList.length>0){
            this.shopList.forEach(ele=>{  
              if(ele.syncTmpMerchantShopId == shopId){
                this.thirdRadio = this.shopMsg.shopId = ele.id;
                 this.shopMsg.shopName = ele.name

              }
            })
          }
          
          // if (!this.shopMsg.shopName) {
          //   this.shopMsg.shopName = this.shopList[0].name;
          //   this.thirdRadio = this.shopMsg.shopId = this.shopList[0].id;
          // }
        }
      });
      await this.getAreas();
    },
    // 获取区域列表
    getAreas() {
      let { shopId } = this.shopMsg;
      getAreas({ shopId }).then((res) => {
        let { data } = res;
        if (data.code == 0) {
          if (data.data.length > 0) {
            data.data.forEach((ele) => {
              ele.text = ele.name;
            });
            this.areasList = data.data;
            this.areaId = data.data[0].id;
            this.getDesk();
          } else {
            this.areasList = [];
          }
        }
      });
    },
    // 当前区域的桌码
    getDesk() {
      let {
        areaId,
        shopMsg: { shopId },
      } = this;
      let params = {
        areaId,
        pageNum: 1,
        pageSize: 999999,
        shopId,
      };
      getDesk(params).then((res) => {
        let { data } = res;
        if (data.code == 0) {
          this.tabList = data.data.list;
        }
      });
    },
    // 获取本地中存储的门店信息
    getLocaShop() {
      let shopMes = localStorage.getItem("shopMsg");
      if (shopMes) {
        this.shopMsg = JSON.parse(shopMes);
        this.thirdRadio = this.shopMsg.shopId;
      }
    },
    // 设置桌号及摄像头调起
    bindDesk(data) {
      this.deskPar = data;
      this.noScan();
    },
    // 绑定桌码

    setDeskCode(data) {
      let dataArr = data.split("/");
      let {
        deskPar: { id, areaName, tableNo },
        areaId,
        areasList,
      shopMsg:{ shopId }

      } = this;
      let params = {
        codeNo: dataArr[dataArr.length - 1],
        bizData: JSON.stringify({ id }),
        dumpPath: `sp-catering/pages/index/main/${dataArr[dataArr.length - 2]}`,
        bizRemark: `${areaName}区域-${tableNo}号`,
        bizShopId:shopId
      };

      Dialog.confirm({
        title: "提示",
        message: `是否绑定${dataArr[dataArr.length - 1]}的二维码？`,
        className: "dialog_class",
        confirmButtonText: "绑定",
        confirmButtonColor: "#ffb72f",
      }).then(() => {
        bindDesk(params).then((res) => {
          let { data } = res;
          if (data.code == 0 && data.msg == "success") {
            Dialog.alert({
              title: "提示",
              message: `绑定桌码成功`,
              confirmButtonColor: "#ffb72f",
            }).then(() => {
              this.getDesk();
            });
          } else {
            Dialog.alert({
              title: "提示",
              message: `${data.msg}`,
              confirmButtonColor: "#ffb72f",
            });
          }
        });
      });
    },
    confirmDialog() {},
    // 摄像头的调用
    noScan() {
      var that = this;
      var u = navigator.userAgent;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        injectedObject.UseScan();
      }
      if (isiOS) {
        function setupWebViewJavascriptBridge(callback) {
          if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
          }
          if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
          }
          window.WVJBCallbacks = [callback]; // 创建一个 WVJBCallbacks 全局属性数组，并将 callback 插入到数组中。
          var WVJBIframe = document.createElement("iframe"); // 创建一个 iframe 元素
          WVJBIframe.style.display = "none"; // 不显示
          WVJBIframe.src = "wvjbscheme://__BRIDGE_LOADED__"; // 设置 iframe 的 src 属性
          document.documentElement.appendChild(WVJBIframe); // 把 iframe 添加到当前文导航上。
          setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe);
          }, 0);
        }
        // 这里主要是注册 OC 将要调用的 JS 方法。
        setupWebViewJavascriptBridge(function (bridge) {
          bridge.callHandler(
            "UseScan",
            { data: "UseScan" },
            function (dataFromOC) {
              console.log(dataFromOC, "dataFromOC--");
              document.getElementById("returnValue").value = dataFromOC;
            }
          );
          bridge.registerHandler(
            "iosSendSNCode",
            function (data, responseCallback) {
              // 回调app
              that.setDeskCode(data);
              responseCallback(responseData);
            }
          );
        });
      }
    },
  },
  // beforeRouteLeave(to, form, next) {
  //   localStorage.setItem("shopMsg", JSON.stringify(this.shopMsg));
  //   next();
  // },
};
</script>
<style lang="less" scoped>
.deck {
  height: 100vh;
  background: #f7f7f7;

  .top_bar {
    position: fixed;
    width: 100%;
  }
}
.content {
  height: calc(100% - 90px);
  overflow-y: auto;
  position: absolute;
  top: 90px;
  width: 100%;
  .shop_address {
    height: 106px;
    background: #fff;
    margin: 20px 0;
    font-size: 34px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #131313;
    padding-left: 33px;
    line-height: 106px;
  }
  .class_ify {
    height: calc(100% - 146px);
    .van-sidebar-item--select::before {
      display: none;
    }
    .van-tree-select__content {
      flex: 4;
    }
    .select_div {
      display: flex;
      justify-content: space-between;
      padding: 35px 0;
      margin-left: 40px;
      width: calc(100% - 40px);
      border-bottom: rgba(231, 231, 231, 0.5) 1px solid;
      align-items: center;
      .desk_num {
        font-size: 32px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #131313;
      }
      .bind {
        font-size: 26px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffb72f;
        display: flex;
        align-items: center;
      }
      .is_bind {
        font-size: 26px;
        font-family: PingFang SC;
        font-weight: 500;
        color: rgba(19, 19, 19, 0.5);
        display: flex;
        align-items: center;
      }
    }
  }
  .pop_shop {
    position: relative;
    height: 50vh;
    .pop_top {
      height: 98px;
      display: flex;
      font-size: 31px;
      align-items: center;
      justify-content: space-between;
      padding: 0 30px;
      background: #f9f9f9;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
    }
    .pop_conent {
      position: absolute;
      top: 173px;
      left: 0;
      height: calc(100% - 95px - 105px);
      padding: 0px 45px 0;
      overflow-y: auto;
      width: 100%;
      // position: relative;
      .pop_radio {
        font-size: 32px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #131313;
        margin-bottom: 45px;
      }
    }
  }
}
.no_content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  /deep/.custom-image {
    .van-empty__image {
      height: 220px;
      width: 340px;
    }
    .van-empty__description {
      font-size: 28px;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(19, 19, 19, 0.7);
      margin-top: 25px;
    }
  }
}
/deep/.con_pop {
  background-color: red !important;
}
.img-icon {
  // width: 80px;
  // height: 80px;
  height: 40px;
}
.confirm_pop {
  background: red;
}
.van-hairline--left {
  .van-button__content {
    background-color: #000 !important;
  }
}
</style>
<style lang="less">
.dialog_class {
  /deep/.van-dialog__cancel {
    color: #ffb72f;
  }
  /deep/.van-dialog__confirm {
    color: #fff !important;
    background-color: #ffb72f !important;
  }
}
</style>
